"""
多维度分析API接口
提供高级数据分析、交叉分析、趋势预测等功能
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from pydantic import BaseModel, Field
from typing import Dict, Any, List, Optional
from datetime import datetime

from core.database import get_db
from core.logging_config import get_logger, log_api_request
from core.auth import get_current_active_user, require_permission
from services.multi_dimension_analysis_service import multi_dimension_analysis_service

# 路由器
multi_dimension_router = APIRouter(tags=["多维度分析"])

# 日志记录器
logger = get_logger("multi_dimension_api")


class CrossAnalysisRequest(BaseModel):
    """交叉分析请求"""
    dimensions: List[str] = Field(..., min_items=2, max_items=5, description="分析维度")
    result_id: Optional[int] = Field(None, description="分析结果ID")
    start_date: Optional[datetime] = Field(None, description="开始日期")
    end_date: Optional[datetime] = Field(None, description="结束日期")
    province: Optional[str] = Field(None, description="省份过滤")
    pollution_type: Optional[str] = Field(None, description="污染类型过滤")


class TrendPredictionRequest(BaseModel):
    """趋势预测请求"""
    predict_days: int = Field(30, ge=1, le=365, description="预测天数")
    result_id: Optional[int] = Field(None, description="分析结果ID")
    start_date: Optional[datetime] = Field(None, description="开始日期")
    end_date: Optional[datetime] = Field(None, description="结束日期")
    province: Optional[str] = Field(None, description="省份过滤")


@multi_dimension_router.post("/cross-analysis")
@log_api_request("cross_analysis")
@require_permission("statistics:view")
async def perform_cross_analysis(
    request: CrossAnalysisRequest,
    current_user=Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """执行交叉分析"""
    logger.info(f"执行交叉分析请求，维度: {request.dimensions}")
    
    try:
        # 构建过滤器
        filters = {}
        if request.start_date:
            filters["start_date"] = request.start_date
        if request.end_date:
            filters["end_date"] = request.end_date
        if request.province:
            filters["province"] = request.province
        if request.pollution_type:
            filters["pollution_type"] = request.pollution_type
        
        # 执行交叉分析
        result = multi_dimension_analysis_service.get_cross_analysis(
            db, request.result_id, request.dimensions, filters
        )
        
        return {
            "success": True,
            "data": result,
            "message": "交叉分析完成"
        }
        
    except Exception as e:
        logger.error(f"交叉分析失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@multi_dimension_router.post("/trend-prediction")
@log_api_request("trend_prediction")
@require_permission("statistics:view")
async def perform_trend_prediction(
    request: TrendPredictionRequest,
    current_user=Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """执行趋势预测"""
    logger.info(f"执行趋势预测请求，预测天数: {request.predict_days}")
    
    try:
        # 构建过滤器
        filters = {}
        if request.start_date:
            filters["start_date"] = request.start_date
        if request.end_date:
            filters["end_date"] = request.end_date
        if request.province:
            filters["province"] = request.province
        
        # 执行趋势预测
        result = multi_dimension_analysis_service.get_trend_prediction(
            db, request.result_id, request.predict_days, filters
        )
        
        return {
            "success": True,
            "data": result,
            "message": "趋势预测完成"
        }
        
    except Exception as e:
        logger.error(f"趋势预测失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@multi_dimension_router.get("/pattern-analysis")
@log_api_request("pattern_analysis")
@require_permission("statistics:view")
async def perform_pattern_analysis(
    result_id: Optional[int] = Query(None, description="分析结果ID"),
    start_date: Optional[datetime] = Query(None, description="开始日期"),
    end_date: Optional[datetime] = Query(None, description="结束日期"),
    province: Optional[str] = Query(None, description="省份过滤"),
    current_user=Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """执行模式分析"""
    logger.info("执行模式分析请求")
    
    try:
        # 构建过滤器
        filters = {}
        if start_date:
            filters["start_date"] = start_date
        if end_date:
            filters["end_date"] = end_date
        if province:
            filters["province"] = province
        
        # 执行模式分析
        result = multi_dimension_analysis_service.get_pattern_analysis(
            db, result_id, filters
        )
        
        return {
            "success": True,
            "data": result,
            "message": "模式分析完成"
        }
        
    except Exception as e:
        logger.error(f"模式分析失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@multi_dimension_router.get("/correlation-analysis")
@log_api_request("correlation_analysis")
@require_permission("statistics:view")
async def perform_correlation_analysis(
    result_id: Optional[int] = Query(None, description="分析结果ID"),
    start_date: Optional[datetime] = Query(None, description="开始日期"),
    end_date: Optional[datetime] = Query(None, description="结束日期"),
    current_user=Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """执行关联性分析"""
    logger.info("执行关联性分析请求")
    
    try:
        # 构建过滤器
        filters = {}
        if start_date:
            filters["start_date"] = start_date
        if end_date:
            filters["end_date"] = end_date
        
        # 执行关联性分析
        result = multi_dimension_analysis_service.get_correlation_analysis(
            db, result_id, filters
        )
        
        return {
            "success": True,
            "data": result,
            "message": "关联性分析完成"
        }
        
    except Exception as e:
        logger.error(f"关联性分析失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@multi_dimension_router.get("/comprehensive")
@log_api_request("comprehensive_analysis")
@require_permission("statistics:view")
async def perform_comprehensive_analysis(
    result_id: Optional[int] = Query(None, description="分析结果ID"),
    start_date: Optional[datetime] = Query(None, description="开始日期"),
    end_date: Optional[datetime] = Query(None, description="结束日期"),
    province: Optional[str] = Query(None, description="省份过滤"),
    current_user=Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """执行综合分析"""
    logger.info("执行综合分析请求")
    
    try:
        # 构建过滤器
        filters = {}
        if start_date:
            filters["start_date"] = start_date
        if end_date:
            filters["end_date"] = end_date
        if province:
            filters["province"] = province
        
        # 执行综合分析
        result = multi_dimension_analysis_service.get_comprehensive_analysis(
            db, result_id, filters
        )
        
        return {
            "success": True,
            "data": result,
            "message": "综合分析完成"
        }
        
    except Exception as e:
        logger.error(f"综合分析失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@multi_dimension_router.get("/dashboard")
@log_api_request("multi_dimension_dashboard")
@require_permission("statistics:view")
async def get_multi_dimension_dashboard(
    result_id: Optional[int] = Query(None, description="分析结果ID"),
    current_user=Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取多维度分析仪表盘"""
    logger.info("获取多维度分析仪表盘请求")
    
    try:
        # 并行获取各种分析数据
        import asyncio
        
        tasks = [
            asyncio.create_task(
                asyncio.to_thread(multi_dimension_analysis_service.get_cross_analysis, db, result_id, ["pollution_type", "region"])
            ),
            asyncio.create_task(
                asyncio.to_thread(multi_dimension_analysis_service.get_trend_prediction, db, result_id, 30)
            ),
            asyncio.create_task(
                asyncio.to_thread(multi_dimension_analysis_service.get_pattern_analysis, db, result_id)
            ),
            asyncio.create_task(
                asyncio.to_thread(multi_dimension_analysis_service.get_correlation_analysis, db, result_id)
            )
        ]
        
        results = await asyncio.gather(*tasks, return_exceptions=True)
        
        # 处理结果
        cross_analysis = results[0] if not isinstance(results[0], Exception) else {}
        trend_prediction = results[1] if not isinstance(results[1], Exception) else {}
        pattern_analysis = results[2] if not isinstance(results[2], Exception) else {}
        correlation_analysis = results[3] if not isinstance(results[3], Exception) else {}
        
        return {
            "cross_analysis": cross_analysis,
            "trend_prediction": trend_prediction,
            "pattern_analysis": pattern_analysis,
            "correlation_analysis": correlation_analysis,
            "summary": {
                "total_cross_correlations": len(cross_analysis.get("cross_analysis", [])),
                "prediction_accuracy": trend_prediction.get("model_accuracy", 0),
                "detected_patterns": len(pattern_analysis.get("patterns", [])),
                "strong_correlations": len(correlation_analysis.get("strong_correlations", [])),
                "analysis_timestamp": datetime.now().isoformat()
            }
        }
        
    except Exception as e:
        logger.error(f"获取多维度分析仪表盘失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@multi_dimension_router.get("/available-dimensions")
@log_api_request("available_dimensions")
@require_permission("statistics:view")
async def get_available_dimensions(
    current_user=Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取可用的分析维度"""
    logger.info("获取可用分析维度请求")
    
    try:
        dimensions = [
            {
                "key": "pollution_type",
                "name": "污染类型",
                "description": "按污染类型分类分析",
                "type": "categorical"
            },
            {
                "key": "region",
                "name": "区域",
                "description": "按省份/城市分类分析",
                "type": "categorical"
            },
            {
                "key": "district",
                "name": "区县",
                "description": "按区县分类分析",
                "type": "categorical"
            },
            {
                "key": "processing_status",
                "name": "处理状态",
                "description": "按处理状态分类分析",
                "type": "categorical"
            },
            {
                "key": "respondent_type",
                "name": "被投诉方类型",
                "description": "按被投诉方类型分类分析",
                "type": "categorical"
            },
            {
                "key": "time",
                "name": "时间",
                "description": "按时间维度分析",
                "type": "temporal"
            }
        ]
        
        return {
            "dimensions": dimensions,
            "max_combinations": 5,
            "min_combinations": 2
        }
        
    except Exception as e:
        logger.error(f"获取可用分析维度失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@multi_dimension_router.get("/export/{analysis_type}")
@log_api_request("export_multi_dimension_analysis")
@require_permission("statistics:export")
async def export_multi_dimension_analysis(
    analysis_type: str,
    format: str = Query("json", description="导出格式"),
    result_id: Optional[int] = Query(None, description="分析结果ID"),
    current_user=Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """导出多维度分析结果"""
    logger.info(f"导出多维度分析结果请求，类型: {analysis_type}, 格式: {format}")
    
    try:
        result = None
        
        if analysis_type == "cross":
            result = multi_dimension_analysis_service.get_cross_analysis(
                db, result_id, ["pollution_type", "region"]
            )
        elif analysis_type == "trend":
            result = multi_dimension_analysis_service.get_trend_prediction(
                db, result_id, 30
            )
        elif analysis_type == "pattern":
            result = multi_dimension_analysis_service.get_pattern_analysis(
                db, result_id
            )
        elif analysis_type == "correlation":
            result = multi_dimension_analysis_service.get_correlation_analysis(
                db, result_id
            )
        elif analysis_type == "comprehensive":
            result = multi_dimension_analysis_service.get_comprehensive_analysis(
                db, result_id
            )
        else:
            raise HTTPException(status_code=400, detail="不支持的分析类型")
        
        if format == "json":
            return {
                "analysis_type": analysis_type,
                "format": "json",
                "data": result,
                "exported_at": datetime.now().isoformat(),
                "exported_by": current_user.username
            }
        elif format == "csv":
            return {"message": "CSV导出功能待实现"}
        else:
            raise HTTPException(status_code=400, detail="不支持的导出格式")
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"导出多维度分析结果失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))